#include "edge_map.hpp"
edge_map::edge_map(std::set<int> vertices,
		   std::multimap<int,int> edges, int d){
  /**
   * *(vert_it) is one of the vertices \f$ v \in V \f$
   */
  std::set<int>::iterator vert_it;
  
  /**
   * edge_it->second is one of the edges \f$ v \in E \f$
   * edge_it->second is one of the edges \f$ w \in E \f$
   * equal_keys->first first of elements with key \f$ w \f$
   * equal_keys->second last of elements with key \f$ w \f$
   */
  std::multimap<int,int>::iterator edge_it;
  std::pair<std::multimap<int,int>::iterator,
	    std::multimap<int,int>::iterator> equal_keys;
  /**
   * emap_it->first contais std::pair<int,int>  p, where
   * p.first is one of the vertices \f$ v \f$ and 
   * p.second is label from set \f$\{0,1,...,d-1\}\f$.
   *
   * emap_it->second contains std::pair<int,int> q, where
   * q.first is \f$ v \f$, e.g. p.first==q.first and
   * q.second is \f$ w \in V \f$, which may be the same as q.first.
   **/
  std::map<intpair,intpair> emap_it;
  
  for(vert_it=vertices.begin();vert_it!=vertices.end();vert_it++){
    
    equal_keys=edges.equal_range(*vert_it);
    
    //Check that there is edge found at vertex (*vert_it)
    if(equal_keys.first==equal_keys.second){
      std::cerr<<"No edges found. Graph is not correctly defined"<<std::endl;
      exit(1);
    }
    //There should be d edges
    if((int) edges.count(*vert_it) != d){
      std::cerr<<"Wrong number of edges found. "
	       <<"There is "<<(int) edges.count(*vert_it)
	       <<" defined, but there should be"
	       <<d<<". Graph is not correctly defined"<<std::endl;
      exit(1);
    }
    
    //Start adding labels
    int edge_direction=0;
    for(edge_it = equal_keys.first;edge_it != equal_keys.second;edge_it++){
      
      intpair label(*vert_it,edge_direction);
      intpair target_edge(edge_it->first,edge_it->second);
      
      //insert label and target edge to the emap
      // e_v^j -> (v,w)
      std::pair<std::map<intpair,intpair>::iterator,bool> ret;
      ret=emap.insert(std::pair<intpair,intpair> (label,target_edge));
      
      //If element e_v^j exists
      if(ret.second==false){
	std::cout<<"Element "<<label.first<<","<<label.second<<" already existed with value "
		 <<target_edge.first<<","<<target_edge.second<<std::endl;
      }
    
    }
  }
}
